<template>
  <div class="haircut-package-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>理发套餐管理</h2>
      <p>管理店内所有理发套餐，包括新增、编辑、删除和状态管理</p>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.totalCount || 0 }}</div>
              <div class="stat-label">总套餐数</div>
            </div>
            <el-icon class="stat-icon"><Box /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card enabled">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.enabledCount || 0 }}</div>
              <div class="stat-label">启用套餐</div>
            </div>
            <el-icon class="stat-icon"><Check /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card disabled">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.disabledCount || 0 }}</div>
              <div class="stat-label">禁用套餐</div>
            </div>
            <el-icon class="stat-icon"><Close /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd" :icon="Plus">
        新增套餐
      </el-button>
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索套餐名称或描述"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
          style="width: 300px"
        >
          <template #append>
            <el-button @click="handleSearch" :icon="Search" />
          </template>
        </el-input>
      </div>
    </div>

    <!-- 套餐列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="packageList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="packageName" label="套餐名称" min-width="150" />
        <el-table-column prop="packagePrice" label="价格" width="120">
          <template #default="{ row }">
            <span class="price">¥{{ row.packagePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="packageDescription" label="套餐描述" min-width="200">
          <template #default="{ row }">
            <el-tooltip :content="row.packageDescription" placement="top" :disabled="!row.packageDescription">
              <span class="description">
                {{ row.packageDescription || '暂无描述' }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.statusText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="packageFormRef"
        :model="packageForm"
        :rules="packageRules"
        label-width="100px"
      >
        <el-form-item label="套餐名称" prop="packageName">
          <el-input
            v-model="packageForm.packageName"
            placeholder="请输入套餐名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="套餐价格" prop="packagePrice">
          <el-input-number
            v-model="packageForm.packagePrice"
            :min="0.01"
            :max="9999.99"
            :precision="2"
            :step="1"
            :disabled="isEdit"
            placeholder="请输入套餐价格"
            style="width: 100%"
          />
          <div v-if="isEdit" class="price-tip">
            <el-text type="info" size="small">
              <el-icon><InfoFilled /></el-icon>
              编辑模式下不允许修改套餐价格
            </el-text>
          </div>
        </el-form-item>
        <el-form-item label="套餐描述" prop="packageDescription">
          <el-input
            v-model="packageForm.packageDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入套餐描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="packageForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Edit,
  Delete,
  Check,
  Close,
  Box,
  InfoFilled
} from '@element-plus/icons-vue'
import {
  getHaircutPackagePage,
  addHaircutPackage,
  updateHaircutPackage,
  deleteHaircutPackage,
  updatePackageStatus,
  getPackageStatistics,
  checkPackageNameExists
} from '@/api/haircutPackage'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const packageList = ref([])
const searchKeyword = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const packageFormRef = ref()

// 统计数据
const statistics = reactive({
  totalCount: 0,
  enabledCount: 0,
  disabledCount: 0
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 表单数据
const packageForm = reactive({
  id: null,
  packageName: '',
  packagePrice: null,
  packageDescription: '',
  status: 1
})

// 表单验证规则
const packageRules = {
  packageName: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' },
    { min: 1, max: 100, message: '套餐名称长度在 1 到 100 个字符', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (!value) return callback()
        try {
          const response = await checkPackageNameExists(value, packageForm.id)
          if (response.data) {
            callback(new Error('套餐名称已存在'))
          } else {
            callback()
          }
        } catch (error) {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  packagePrice: [
    {
      required: true,
      message: '请输入套餐价格',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        // 编辑模式下不验证价格
        if (isEdit.value) {
          callback()
          return
        }
        if (!value) {
          callback(new Error('请输入套餐价格'))
          return
        }
        if (value < 0.01 || value > 9999.99) {
          callback(new Error('价格必须在 0.01 到 9999.99 之间'))
          return
        }
        callback()
      }
    }
  ],
  packageDescription: [
    { max: 500, message: '描述长度不能超过 500 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 生命周期
onMounted(() => {
  loadPackageList()
  loadStatistics()
})

// 方法
const loadPackageList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      size: pagination.size,
      keyword: searchKeyword.value
    }
    const response = await getHaircutPackagePage(params)
    packageList.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('加载套餐列表失败')
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    const response = await getPackageStatistics()
    Object.assign(statistics, response.data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadPackageList()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadPackageList()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadPackageList()
}

const handleAdd = () => {
  resetForm()
  isEdit.value = false
  dialogTitle.value = '新增套餐'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  resetForm()
  Object.assign(packageForm, {
    id: row.id,
    packageName: row.packageName,
    packagePrice: row.packagePrice,
    packageDescription: row.packageDescription,
    status: row.status
  })
  isEdit.value = true
  dialogTitle.value = '编辑套餐'
  dialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    await packageFormRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      await updateHaircutPackage(packageForm.id, packageForm)
      ElMessage.success('更新套餐成功')
    } else {
      await addHaircutPackage(packageForm)
      ElMessage.success('新增套餐成功')
    }
    
    dialogVisible.value = false
    loadPackageList()
    loadStatistics()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    submitLoading.value = false
  }
}

const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const action = newStatus === 1 ? '启用' : '禁用'
    
    await ElMessageBox.confirm(
      `确定要${action}套餐"${row.packageName}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updatePackageStatus(row.id, newStatus)
    ElMessage.success(`${action}套餐成功`)
    loadPackageList()
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`操作失败`)
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除套餐"${row.packageName}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteHaircutPackage(row.id)
    ElMessage.success('删除套餐成功')
    loadPackageList()
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除套餐失败')
    }
  }
}

const resetForm = () => {
  Object.assign(packageForm, {
    id: null,
    packageName: '',
    packagePrice: null,
    packageDescription: '',
    status: 1
  })
  nextTick(() => {
    packageFormRef.value?.clearValidate()
  })
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}
</script>

<style scoped>
.haircut-package-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
}

.stat-card.enabled {
  border-left: 4px solid #67c23a;
}

.stat-card.disabled {
  border-left: 4px solid #f56c6c;
}

.stat-content {
  position: relative;
  z-index: 2;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 48px;
  color: #e4e7ed;
  z-index: 1;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.price {
  color: #e6a23c;
  font-weight: 600;
}

.description {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

.price-tip {
  margin-top: 5px;
}

.price-tip .el-text {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style> 